<?php

namespace app\api\service;

use app\common\Jwt;
use app\model\SystemSetting;
use app\model\User;
use app\service\MiniappService;
use app\traits\UserTrait;
use think\facade\Request;
use think\helper\Arr;

class UserService
{
    use UserTrait;

    public function miniapplogin(array $data): array
    {
        [$isOk, $code2session] = MiniappService::code2session($data['code']);
        if (!$isOk) {
            return [false, $code2session];
        }
        $openid = $code2session['openid'] ?? '';
        $sessionKey = $code2session['session_key'] ?? '';
        $unionId = $code2session['unionid'] ?? '';

        if (!$openid) {
            return [false, '身份信息获取失败'];
        }

        $datetime = date('Y-m-d H:i:s');
        /** @var User $user */
        if (!$user = User::where(['wx_openid' => $openid])->find()) {
            $user = User::create([
                'wx_openid' => $openid,
                'username' => uniqid('wx'),
                'wx_session_key' => $sessionKey,
                'wx_unionid' => $unionId,
                'created_at' => $datetime,
                'updated_at' => $datetime,
                'login_time' => $datetime,
                'login_ip' => Request::ip()
            ]);
        } else {
            $user->save([
                'login_time' => $datetime,
                'login_ip' => Request::ip()
            ]);
        }
        $data = [
            'token' => Jwt::getUserToken($user->id, 'api'),
            'username' => Arr::get($user, 'username', ''),
            'nickname' => $this->getNickname($user),
            'avatar' => $this->getAvatar($user), //优先获取上传的图像
            'phone_number' => Arr::get($user, 'phone', ''),
        ];
        return [true, $data];
    }

    /**
     * 更新通用信息，支持从token获取用户ID
     * @param $data
     * @param int $id
     * @return array
     */
    public function update($data, $id = 0): array
    {
        //图像类型前端只传了url，默认只存url
        $id = $this->getUid($id) ?: $this->getUidFromToken(Arr::get($data, 'token'));
        unset($data['token']);
        return [true, User::update($data, ['id' => $id])];
    }

    /**
     * 更新手机号
     * @param string $code
     * @param int $uid
     * @return array
     */
    public function updatePhone(string $code, int $uid = 0): array
    {
        [$isOk, $phoneInfo] = MiniappService::getPhoneNumber($code);
        if (!$isOk) {
            return [false, $phoneInfo];
        }
        $model = User::update(['phone' => Arr::get($phoneInfo, 'phone_info.phoneNumber')], ['id' => $this->getUid($uid)]);
        return [true, $model];
    }

    /**
     * 判断图片是否违规
     * @param User $user
     * @return array|\ArrayAccess|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAvatar(User $user)
    {
        if ($user->avatar_id_status == 2) {
            $setting = SystemSetting::query()->order('id', 'desc')->find();
            return Arr::get($setting, 'image_forbidden.url');
        }
        return Arr::get($user, 'avatar_upload.url', Arr::get($user, 'avatar', ''));
    }

    /**
     * 判断昵称是否违规
     * @param User $user
     * @return array|\ArrayAccess|mixed|string
     */
    public function getNickname(User $user)
    {
        if ($user->nickname_status == 2) {
            return '违规的昵称';
        }
        return Arr::get($user, 'nickname', '');
    }
}